import {
  HttpException,
  HttpStatus,
  Inject,
  Injectable,
  NotFoundException,
  Scope,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
import { Event } from 'src/events/entities/event.entity';
import { Connection, QueryRunner, Repository } from 'typeorm';
import { CreateArticlesDto } from './dto/create-articles.dto';
import { UpdateArticlesDto } from './dto/update-articles.dto';
import { Articles } from './entities/articles.entity';

@Injectable({ scope: Scope.REQUEST })
export class ArticlesService {
  constructor(
    @InjectRepository(Articles)
    private readonly articlesRepository: Repository<Articles>,

    private readonly connection: Connection,
  ) {}

  findAll(paginationQuery: PaginationQueryDto) {
    const { limit, offset } = paginationQuery;
    return this.articlesRepository.find({
      relations: ['flavors'],
      skip: offset,
      take: limit,
    });
  }

  async findOne(id: string) {
    // const dataItem = await this.articlesRepository.findOneBy({
    //   id: Number(id)
    // });

    const dataItem = await this.articlesRepository.find({
      where: {
        id: Number(id),
      },
      relations: ['flavors'],
    });
    if (!dataItem) {
      // throw new NotFoundError
      throw new HttpException(`找不到id为${id}的资源`, HttpStatus.NOT_FOUND);
      // throw new NotFoundException(`找不到id为${id}的资源`);
    }

    return dataItem;
  }

  async create(body: CreateArticlesDto) {
    const item = this.articlesRepository.create({ ...body });

    return this.articlesRepository.save(item); // 返回一个promise
  }

  async update(id: string, body: UpdateArticlesDto) {
    /* 如果表里面找不到对应的id，则直接返回undefined */
    const item = await this.articlesRepository.preload({
      id: Number(id),
      ...body,
    });

    if (!item) {
      throw new NotFoundException(`articles #${id} not found`);
    }
    return this.articlesRepository.save(item);
  }

  async remove(id: string) {
    const articles = await this.findOne(id);

    return this.articlesRepository.remove(articles);
  }
}
